<template>
  <ContentWrap class="chem-record-wrap">

    <!-- 表格 -->
    <el-table
      :data="form.table"
      border
      class="chem-table"
      stripe
      :span-method="arraySpanMethod"
    >
      <el-table-column align="center" label="工作场所" prop="workplace">
        <template #default="{ row }">
          <el-input v-model="row.workplace" placeholder="" @change="handleTableDataChange" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="检测岗位" prop="detectionPost">
        <template #default="{ row }">
          <el-input v-model="row.detectionPost" placeholder="" @change="handleTableDataChange" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="区域i" prop="samplePoint">
        <template #default="{ row }">
          <el-input v-model="row.samplePoint" placeholder="" @change="handleTableDataChange" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="对应测量点j" prop="samplePoint">
        <template #default="{ row }">
          <el-input v-model="row.samplePoint" placeholder="" @change="handleTableDataChange" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="测量点电场强度Ej(V/m)" prop="ej">
        <template #default="{ row }">
          <el-input v-model="row.ej" placeholder="" @change="handleTableDataChange" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="区域电场强度Ei(V/m)" prop="ei">
        <template #default="{ row }">
          <el-input v-model="row.ei" placeholder="" @change="handleTableDataChange" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="代表时间(h)" prop="representativeTime">
        <template #default="{ row }">
          <el-input v-model="row.representativeTime" placeholder="" @change="handleTableDataChange" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="工频电场8h时间加权平均值 Es (V/m)" prop="e8">
        <template #default="{ row }">
          <el-input v-model="row.e8" placeholder="" @change="handleTableDataChange" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="备注" prop="remark" width="120">
        <template #default="{ row }">
          <el-input v-model="row.remark" placeholder="" @change="handleTableDataChange" />
        </template>
      </el-table-column>
    </el-table>
  </ContentWrap>
</template>

<script lang="ts" setup>
import { onMounted, ref, watch } from 'vue'
import ContentWrap from '@/components/ContentWrap/src/ContentWrap.vue'

// 定义表格行数据类型（工频电场）
interface PowerFrequencyTableRow {
  workplace: string // 工作场所
  detectionPost: string // 检测岗位
  samplePoint: string // 区域i
  samplePoint: string // 对应测量点j
  ej: string // 测量点电场强度 Ej (V/m)
  ei: string // 区域电场强度 Ei (V/m)
  representativeTime: string // 代表时间 (h)
  e8: string // 工频电场 8h 时间加权平均值 Es (V/m)
  remark: string // 备注
}

// 定义传入数据的结构
interface HighTempFormDataItem {
  sampleMethod: string
  samplePoint: string
  strengthType: string
  workDays: string
  distance: string
  workContent: string
  measuringEquipment: string
  workHours: string
  source: string
  sampleNo: string
  sampleDuration: string
  personalProtective: string
  duration: number
  sampleCount: string
  protectionFacilityStatus: string
  heatUniform: string
  dw: string
  tih: string
  productionStatus: string
  flowRate: string
  protectionStatus: string
  noiseType: string
  uvSpectrumType: string
  worker: any[]
  earWearStatus: string
  sampleDays: string
  contactTime: string
  longShortTime: string
  airCollector: string
  laeqTe: string
  heatSourceStable: string
  lowThreshold: string
  dtectionSite: string
  count: number
  detectionPost: string
  contactTiming: string
  pointCount: string
  earProtection: string
  detectionType: string
  samplingPeriod: number
  interval: number
  workplace: string
  item: string
  laeqTi: string
  dh: string
  storageLife: string
  lex8h: string
  lexW: string
  remark: string
}

// 定义表单数据类型
interface PowerFrequencyFormData {
  type: string // 检测类别
  table: PowerFrequencyTableRow[] // 表格数据
}

// 新增type和formData prop
const props = defineProps<{
  formData?: any
}>()

const emit = defineEmits(['change'])

defineOptions({ name: 'PowerFrequencyDataProcessing' })

const emitChange = () => {
  emit('change', { ...form.value })
}


// 监听表格数据变化，自动计算
const handleTableDataChange = () => {
  if (!form.value?.table) return
  emitChange()
}

// 响应式form，并与父组件传入的formData合并
const form = ref<PowerFrequencyFormData>({
  type: '',
  table: []
})

// 将传入的数据转换为表格行数据
const convertToTableRows = (data: HighTempFormDataItem[]): PowerFrequencyTableRow[] => {
  return data.map((item) => {
    return {
      workplace: item.workplace || '/',
      detectionPost: item.detectionPost || '/',
      samplePoint: item.samplePoint || '/',
      samplePoint: item.samplePoint || '/',
      ej: item.ej || '/',
      ei: item.ei || '/',
      representativeTime: item.representativeTime || '/',
      e8: item.e8 || '/',
      remark: item.remark || '/'
    }
  })
}

// 监听父组件formData变化，重新合并为本地form
watch(
  () => props.formData,
  (val) => {
    if (val && Array.isArray(val)) {
      form.value.table = convertToTableRows(val)
      form.value.type = 'power_frequency' // 设置检测类别为工频电场
      handleTableDataChange()
      console.log('转换后的表格数据:', JSON.stringify(form.value))
    }
  },
  { immediate: true }
)

// 暴露数据与方法给父组件
defineExpose({
  form
})

// 合并单元格方法
const arraySpanMethod = ({ row, column, rowIndex, columnIndex }: any) => {
  if (!form.value.table || form.value.table.length === 0) {
    return [1, 1]
  }

  // 前三列分组合并：
  // 第1列：按自身；第2列：第1+2；第3列：第1+2+3
  if (columnIndex === 0 || columnIndex === 1 || columnIndex === 2) {
    const getGroupKey = (r: any) => {
      if (columnIndex === 0) return `${r.workplace}`
      if (columnIndex === 1) return `${r.workplace}__${r.detectionPost}`
      return `${r.workplace}__${r.detectionPost}__${r.samplePoint}`
    }

    const currentKey = getGroupKey(form.value.table[rowIndex])

    if (rowIndex > 0) {
      const prevKey = getGroupKey(form.value.table[rowIndex - 1])
      if (prevKey === currentKey) {
        return [0, 0]
      }
    }

    let rowspan = 1
    for (let i = rowIndex + 1; i < form.value.table.length; i++) {
      const nextKey = getGroupKey(form.value.table[i])
      if (nextKey === currentKey) {
        rowspan++
      } else {
        break
      }
    }
    return [rowspan, 1]
  }

  return [1, 1]
}

onMounted(() => {})
</script>

<style lang="scss" scoped>
.chem-title {
  font-size: 26px;
  font-weight: 600;
  color: #222;
  flex-grow: 1;
  text-align: center;
}

.chem-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 0 0 24px 0;
  padding: 16px 0 16px 0;
  border-bottom: 1.5px solid #409eff;
  font-size: 20px;
  font-weight: 600;
  color: #409eff;
  background: none;
  border-radius: 0;
  box-shadow: none;
  letter-spacing: 1px;
}

.chem-form {
  background: none;
  box-shadow: none;
  border-radius: 0;
  margin-bottom: 0;

  :deep(.el-input__inner) {
    border-radius: 0 !important;
    box-shadow: none !important;
  }

  :deep(.el-form-item__label) {
    white-space: nowrap;
  }
}

.chem-btns {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
  align-items: center;
  margin-top: 0;
}

.chem-table {
  margin-top: 18px;
  --el-table-border-radius: 0 !important;
  --el-table-header-bg-color: #f7f8fa;
  --el-table-border-color: #e5e6eb;
  box-shadow: none !important;
  border-radius: 0 !important;

  :deep(.el-table__header th) {
    background: #f7f8fa !important;
    font-weight: 600;
    font-size: 14px;
    border-radius: 0 !important;
    padding: 8px 0 !important;

    .cell {
      padding-left: 0px !important;
      padding-right: 0px !important;
    }
  }

  // 设置表格行高
  :deep(.el-table__body td) {
    border-radius: 0 !important;

    font-size: 14px;
    padding: 0 !important;
    // 列和单元格的边距
    .cell {
      padding: 0px 0px;
    }
  }

  // 去掉输入框边框
  :deep(.el-input__wrapper) {
    border-radius: 0 !important;
    box-shadow: none !important;
  }

  // 针对下拉选择框的所有相关元素去掉边框
  :deep(.el-select__wrapper) {
    border: none !important;
    box-shadow: none !important;
  }
}

.input-with-unit {
  position: relative;
}

.unit-text {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  color: #909399;
  font-size: 14px;
  pointer-events: none;
  z-index: 1;
}
</style>
